<?php

namespace app\modules\index\services;

use app\common\services\BaseService;
use app\models\Activity;
use Carbon\Carbon;

class ActivityService extends BaseService{

    /**
     * 搜索
     * @param $merchant_id
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function search($merchant_id){
        $query = Activity::find()
            ->asArray(true)
            ->orderBy(['act_id'=>SORT_DESC])
            ->andWhere("'". Carbon::now()->toDateString() ."' between start_time and end_time");

        if(!empty($merchant_id)){
            $query->andWhere(['merchant_id'=>$merchant_id]);
        }

        return $query->all();
    }

    /**
     * 计算优惠金额
     * @param $total_price
     * @param $merchant_id
     * @return mixed
     */
    public static function calc($total_price,$merchant_id){
        $acts = self::search($merchant_id);
        $data['coupon_price'] = 0;
        $data['act_info'] = null;
        foreach($acts as $k=>$v){
            if($total_price >= $v['min_amount']){
                if($v['type'] == 1){
                    $temp = $v['content'];
                }else{
                    $temp = round($total_price * $v['content'],2);
                }
                if($data['coupon_price'] < $temp){
                    $data['coupon_price'] = $temp;
                    $data['act_info'] = $acts[$k];
                }
            }
        }
        return $data;
    }
}